package com.wenhao.leetcode.easy;

/**
 * 题目：https://leetcode-cn.com/problems/maximum-subarray/submissions/
 * 最大子序和
 *
 * 滑动窗口
 * 如果当前的窗口之和小于零的话，那么可以舍弃当前的窗口，直接从下一个数计算，因为保留了当前窗口计算出来的值反而会比不计算的要小
 * @author Wenhao Tong
 * @Description
 * @create 2021-06-29 11:21
 */
public class LeetCode53 {

    public static void main(String[] args) {
        LeetCode53 leetCode53 = new LeetCode53();
        int maxSubArray = leetCode53.maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4});
        System.out.println(maxSubArray);
    }

    public int maxSubArray(int[] nums) {
        int right = 0;
        int max = nums[0];
        int sum = 0;
        while (right < nums.length) {
            sum += nums[right];
            if (sum > max) {
                max = sum;
            }
            if (sum <= 0) {
                sum = 0;
            }
            right++;
        }
        return max;
    }


}
